package com.cucn.ingmall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.cucn.ingmall.order.config.AlipayTemplate;
import com.cucn.ingmall.order.service.OrderService;
import com.cucn.ingmall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 订单支付成功监听
 *
 * @author KouChaoJie
 * @since: 2022/2/10 09:56
 */
@RestController
@Slf4j
public class OrderPayedListener {
    @Resource
    private OrderService orderService;
    @Resource
    private AlipayTemplate alipayTemplate;

    /**
     * 处理支付宝异步通知回调
     *
     * @param request
     * @return
     */
    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException {
        //只要我们收到了支付宝给我们的异步通知，告诉我们订单支付成功.返回success，支付宝就不再通知
//        Map<String, String[]> map = request.getParameterMap();
//        for (String key : map.keySet()) {
//            String parameter = request.getParameter(key);
//            log.info("参数名:{},参数值:{}", key, parameter);
//        }
//        log.info("支付宝通知到位了...数据:{}", map);

        //验签
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type());

        if (signVerified) {
            log.info("签名验证成功");
            String result = orderService.handlePayResult(payAsyncVo);

            return result;
        } else {
            log.info("签名验证失败");
            return "error";
        }


    }
}
